from flask import Blueprint, render_template, request
from flask_jwt_extended import jwt_required, get_current_user
from orms import UserORM, ArticleORM
from com.store_file import save_avatar, save_article_index_image, save_article_content_image
from werkzeug.datastructures import FileStorage
from extensions import db

my_bp = Blueprint('my', __name__)


@my_bp.get('/my/<int:user_id>')
@jwt_required()
def my_view(user_id):
    current_user: UserORM = get_current_user()
    return render_template('my/index.html',
                           current_user=current_user)


# 收藏列表
@my_bp.get('/my/collection/')
@jwt_required()
def collection():
    current_user: UserORM = get_current_user()
    page = request.args.get('page', default=1, type=int)
    per_page = request.args.get('limit', default=10, type=int)

    # 作者的文章列表
    pag = current_user.collection_article_list.paginate(page=page, per_page=per_page, error_out=False)

    return render_template('my/collection.html', pag=pag)


@my_bp.get('/my/articles/')
@jwt_required()
def articles():
    current_user: UserORM = get_current_user()
    page = request.args.get('page', default=1, type=int)
    per_page = request.args.get('limit', default=10, type=int)
    pag = current_user.article_list.order_by(ArticleORM.create_at.desc()).paginate(page=page, per_page=per_page, error_out=False)

    return render_template('my/articles.html', pag=pag)


# 关注列表
@my_bp.get('/my/followed/')
@jwt_required()
def followed():
    current_user: UserORM = get_current_user()
    page = request.args.get('page', default=1, type=int)
    per_page = request.args.get('limit', default=10, type=int)

    # 作者的文章列表
    pag = current_user.followed.paginate(page=page, per_page=per_page, error_out=False)

    return render_template('my/followed.html', pag=pag, current_user=current_user)


# 请求个人中心页面
@my_bp.get('/my/user_id=<int:user_id>')
@jwt_required()
def user_(user_id):
    current_user = get_current_user()
    return render_template('my/user_info.html',
                           current_user=current_user)


# 个人信息界面
@my_bp.get('/my/base_info/')
@jwt_required()
def base_info():
    current_user = get_current_user()
    return render_template('my/base_info.html',
                           current_user=current_user)


# 修改个人基本信息
@my_bp.post('/my/info/')
@jwt_required()
def info_post():
    data = request.get_json()
    current_user: UserORM = get_current_user()
    current_user.create_at = data['create_at']
    current_user.nick_name = data['nickname']
    current_user.gender = data['gender']
    current_user.signature = data['signature']
    current_user.save()
    return {
        "code": 0,
        "message": "信息修改成功"
    }


# 上传头像
@my_bp.post('/my/avatar/')
@jwt_required()
def upload_pic():
    current_user: UserORM = get_current_user()
    files = request.files
    avatar_file: FileStorage = files.get('file')
    # print(avatar_file)
    # print(dir(avatar_file))
    url = save_avatar(avatar_file)
    current_user.avatar_url = url
    current_user.save()
    return {
        "code": 0,
        "message": "上传成功",
        "url": url
    }


# 修改密码
@my_bp.post('/my/reset_password/')
@jwt_required()
def reset_password():
    current_user: UserORM = get_current_user()
    old_password = request.json.get('old_password')
    new_password = request.json.get('new_password')
    # print(old_password,new_password)
    if not current_user.check_passwd(old_password):
        return {
            "code": -1,
            "message": "原密码错误"
        }
    elif current_user.check_passwd(new_password):
        return {
            "code": -1,
            "message": "修改失败，原密码与新密码一致"
        }
    # 校验成功后，修改密码，重定向到登陆界面
    current_user.password = new_password
    current_user.save()
    return {
        'code': 0,
        "message": "修改成功"
    }


# 文章编辑
@my_bp.get('/my/article_release/')
@jwt_required()
def article_release():
    return render_template('my/article_release.html')


# 上传文章首页图片，返回图片url
@my_bp.post('/my/article_index_image/')
@jwt_required()
def article_index_image():
    files = request.files
    article_index_image_file: FileStorage = files.get('file')
    url = save_article_index_image(article_index_image_file)
    # 文章封面与文章绑定--->未实现
    return {
        "code": 0,
        "message": "上传成功",
        "article_index_image_url": url
    }


# 上传文章内部图片
@my_bp.post('/my/article_upload/')
@jwt_required()
def article_content_image():
    files = request.files
    article_content_image_file: FileStorage = files.get('wangeditor-uploaded-image')
    try:
        url = save_article_content_image(article_content_image_file)
    except Exception as e:
        return {
            "errno": 1,
            "message": "error"
        }
    return {  # wangEdit 的格式
        "errno": 0,
        "data": {
            "url": url,
            "href": url
        }
    }


# 上传文章内容
@my_bp.post('/my/posts_release/')
@jwt_required()
def posts_release():
    current_user: UserORM = get_current_user()
    data = request.get_json()
    article_obj: ArticleORM = ArticleORM()
    article_obj.title = data.get('title')
    article_obj.content = data.get('content')
    article_obj.category_id = data.get('category_id')
    article_obj.digest = data.get('digest')
    article_obj.index_image_url = data.get('index_image_url')
    article_obj.status = 1
    article_obj.user_id = current_user.id
    article_obj.source = current_user.nick_name
    article_obj.save()
    return {
        "code": 0,
        "message": "上传成功, 等待审核通过",
    }